<?php
/*
 * 使用动态缓存机制
* 获取 设置config表中的key-value值
*/
function wx_val($key,$value){
	if(is_string($key) && is_null($value)){
		$data=M("wx_config")->getField("_key,_value");
		//$data=v_cache();
		return $data[$key];
	}else if(is_string($value)){
		M("wx_config")->where("_key='{$key}'")->setField('_value',$value);
		//$data=v_cache(true);
	}else if(is_array($key)){
		//批量赋值
		foreach($key as $k=>$v){
			M("wx_config")->where("_key='{$k}'")->setField('_value',$v);
		}
		//$data=v_cache(true);
	}
}

/*
 * 辅助V方法完成key-value的动态缓存
* $bool表是否重新缓存
*/
function v_cache($bool){
	$rst=F('v_cache');
	if(empty($rst) || $bool){
		$data=M("wx_config")->getField("_key,_value");
		F('v_cache',$data);
		return $data;
	}else{
		return $rst;
	}


}

/**
 * 获取access_token
 * 可以使用memcache
 * @return [type] [description]
 * 3.13
 */
function get_access_token(){
    $access_token = M('access_token')->where('id=1')->getField('access_token');
    $updatetime   = M('access_token')->where('id=1')->getField('updatetime');
    $url          = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".C('APPID')."&secret=".C('APPSECRET');
    if( !empty($updatetime) ){

        if( $access_token == ''){    
            //echo '为空更新中';     
            $str=xcurl($url);

            $str=json_decode($str);
            $access_token=$str->access_token;
            $data['access_token']=$access_token;
            $data['updatetime']=time();
            $res=M('access_token')->where('id=1')->save($data);
            if($res){
              return $access_token;
            }else{
              //echo '更新失败';
              return false;
            }
        }
        if( ( $updatetime-time() ) < -3600) {     //超过7200秒了
            //echo '过期更新中';
            $str=xcurl($url);
            $str=json_decode($str);
            $access_token=$str->access_token;
            $data['access_token']=$access_token;
            $data['updatetime']=time();
            $res=M('access_token')->where('id=1')->save($data);
            if($res){
              return $access_token;
            }else{
              echo '更新失败';
              return false;
            }
        }else{//未过期
          //echo '未过期';
          return $access_token;
        }

    } else {
        $sql = 'ALTER TABLE  `access_token` AUTO_INCREMENT =1';
        $res = M('')->query($sql);
        
        $str                  = xcurl($url);
        $str                  = json_decode($str);
        $access_token         = $str->access_token;
        $data['access_token'] = $access_token;
        $data['updatetime']   = time();
        // pe($data);
        $res                  = M('access_token')->add($data);

        return $access_token; 
    }

}

function get_user_info($openid,$access_token,$postObj = ''){
    $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid";
    // returnText($postObj,$url);
    $userinfo = file_get_contents($url);
    $info = json_decode($userinfo);
    if(empty($info->nickname)){
      return '';
    }
    $data = array(
        'openid'   => $openid.'', //$openid 不是字符串型
        'nickname' => $info->nickname,
        'sex'      => $info->sex,
        'address'  => $info->country.' '.$info->province.' '.$info->city,
        'headimgurl' => $info->headimgurl,
        'subscribe_time' => $info->subscribe_time,
        'updatetime' => time()
    );
    return $data;
}


/**
 * 更新菜单
 */
function UpdateMenu(){
    $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".get_access_token();

//     $menu = '
// {
//     "button": [
//         {
//             "type": "click", 
//             "name": "我要兑券", 
//             "key": "exchange"
//         }, 
//         {
//             "type": "click", 
//             "name": "我要查询", 
//             "key": "find"
//         }
//     ]
// }
// ';       

$menu = '
{
    "button": [
        {
            "type": "view", 
            "name": "我要兑券", 
            "url": "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe3505419db885a9a&redirect_uri='.urlencode('http://single.wzxing.com/Weixin/index.html').'&response_type=code&scope=snsapi_base&state=1#wechat_redirect"
        }, 
        {
           "name":"我要查询",
           "sub_button":[
            {
                "type": "click", 
                "name": "我的蟹卡", 
                "key": "find"
            },
            {
               "type":"view",
               "name":"我的信息",
               "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe3505419db885a9a&redirect_uri='.urlencode('http://single.wzxing.com/Weixin/address.html').'&response_type=code&scope=snsapi_base&state=1#wechat_redirect"
            }]
       }
    ]
}
';    
// $menu = '
//  {
//      "button":[
//      {  
//           "type":"click",
//           "name":"今日歌曲",
//           "key":"V1001_TODAY_MUSIC"
//       },
//       {
//            "type":"click",
//            "name":"歌手简介",
//            "key":"V1001_TODAY_SINGER"
//       },
//       {
//            "name":"菜单",
//            "sub_button":[
//            {  
//                "type":"view",
//                "name":"搜索",
//                "url":"http://www.soso.com/"
//             },
//             {
//                "type":"view",
//                "name":"视频",
//                "url":"http://v.qq.com/"
//             },
//             {
//                "type":"click",
//                "name":"赞一下我们",
//                "key":"V1001_GOOD"
//             }]
//        }]
//  }
// ';


    $data = request_by_other($url,$menu );

    return $data;

}

/**
 * post
 * @param  [type] $url      [description]
 * @param  [type] $jsonData [description]
 * @return [type]           [description]
 */
function curl_post($url,$jsonData){          //微信POST
    $ch = curl_init($url) ;
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS,$jsonData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

    $result = curl_exec($ch) ;
    curl_close($ch) ;
    return $result;
}

function _curl_post($url, $vars) {       
    $ch = curl_init();    
    curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);      
    curl_setopt($ch, CURLOPT_URL,$url);     
    curl_setopt($ch, CURLOPT_POST, 1 );  
    curl_setopt($ch, CURLOPT_HEADER, 0 ) ;  
    curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);     
    $data = curl_exec($ch);        
    curl_close($ch);      
    if ($data)   
        return $data;     
    else
        return false;     
} 

function posttohost($url, $data) {
  $url = parse_url($url);
  if (!$url) return "couldn't parse url";
  if (!isset($url['port'])) { $url['port'] = ""; }
  if (!isset($url['query'])) { $url['query'] = ""; }

  $encoded = "";

  while (list($k,$v) = each($data)) {
    $encoded .= ($encoded ? "&" : "");
    $encoded .= rawurlencode($k)."=".rawurlencode($v);
  }

  $fp = fsockopen($url['host'], $url['port'] ? $url['port'] : 80);
  if (!$fp) return "Failed to open socket to $url[host]";

  fputs($fp, sprintf("POST %s%s%s HTTP/1.0/n", $url['path'], $url['query'] ? "?" : "", $url['query']));
  fputs($fp, "Host: $url[host]/n");
  fputs($fp, "Content-type: application/x-www-form-urlencoded/n");
  fputs($fp, "Content-length: " . strlen($encoded) . "/n");
  fputs($fp, "Connection: close/n/n");

  fputs($fp, "$encoded/n");

  $line = fgets($fp,1024);
  if (!eregi("^HTTP/1/.. 200", $line)) return;

  $results = ""; $inheader = 1;
  while(!feof($fp)) {
    $line = fgets($fp,1024);
    if ($inheader && ($line == "/n" || $line == "/r/n")) {
      $inheader = 0;
    }
    elseif (!$inheader) {
      $results .= $line;
    }
  }
  fclose($fp);

  return $results;
}

/**
 * Curl版本
 * 使用方法：
 * $post_string = "app=request&version=beta";
 * request_by_curl('http://facebook.cn/restServer.php',$post_string);
 */
function request_by_curl($remote_server, $post_string)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $remote_server);
    curl_setopt($ch, CURLOPT_POSTFIELDS, 'mypost=' . $post_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, "Jimmy's CURL Example beta");
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
} 
 
 
/**
 * 其它版本
 * 使用方法：
 * $post_string = "app=request&version=beta";
 * request_by_other('http://facebook.cn/restServer.php',$post_string);
 */
function request_by_other($remote_server, $post_string)
{
    $context = array(
        'http' => array(
            'method' => 'POST',
            'header' => 'Content-type: application/x-www-form-urlencoded' .
                        '\r\n'.'User-Agent : Jimmy\'s POST Example beta' .
                        '\r\n'.'Content-length:' . strlen($post_string) + 8,
            'content' => $post_string)
        );
    $stream_context = stream_context_create($context);
    $data = file_get_contents($remote_server, false, $stream_context);
    return $data;
} 

/**
            return消息
 */
//写到一个新的function文件引入returnFun
/**
 * 回复文本信息
 * @param  [type] $postObj    [description]
 * @param  [type] $contentStr [description]
 * @return [type]             [description]
 */
function returnText($postObj,$contentStr){
    $fromUsername = $postObj->FromUserName;
    $toUsername = $postObj->ToUserName;
    $time = time();
    $textTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[%s]]></MsgType>
        <Content><![CDATA[%s]]></Content>
        <FuncFlag>0</FuncFlag>
        </xml>";
    $msgType = "text";
    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
    echo $resultStr;
    exit;
}

/**
 * 回复图片信息
 * @param  [type] $postObj [description]
 * @param  [type] $MediaId [description]
 * @return [type]          [description]
 */
function returnImage($postObj,$MediaId){
    $fromUsername = $postObj->FromUserName;
    $toUsername = $postObj->ToUserName;
    $time = time();
    $textTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[image]]></MsgType>
        <Image>
        <MediaId><![CDATA[%s]]></MediaId>
        </Image>
        </xml>";
    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $MediaId);
    echo $resultStr;
    exit;
}

/**
 * 回复语音消息
 * @param  [type] $postObj [description]
 * @param  [type] $MediaId [description]
 * @return [type]          [description]
 */
function returnVoice($postObj,$MediaId){
    $fromUsername = $postObj->FromUserName;
    $toUsername = $postObj->ToUserName;
    $time = time();
    $textTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[voice]]></MsgType>
        <Voice>
        <MediaId><![CDATA[%s]]></MediaId>
        </Voice>
        </xml>";
    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $MediaId);
    echo $resultStr;
    exit;
}

/**
 * 回复视频消息
 * @param  [type] $postObj     [description]
 * @param  [type] $MediaId     [通过上传多媒体文件，得到的id]
 * @param  [type] $title       [视频消息的标题]
 * @param  [type] $description [视频消息的描述]
 * @return [type]              [description]
 */
function returnVideo($postObj,$MediaId,$title,$description){
    $fromUsername = $postObj->FromUserName;
    $toUsername = $postObj->ToUserName;
    $time = time();
    $textTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[video]]></MsgType>
        <Video>
        <MediaId><![CDATA[%s]]></MediaId>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        </Video> 
        </xml>";
    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $MediaId,$title,$description);
    echo $resultStr;
    exit;
}

/**
 * 回复音乐消息
 * @param  [type] $postObj      [description]
 * @param  [type] $title        [音乐标题]
 * @param  [type] $description  [音乐描述]
 * @param  [type] $musicUrl     [音乐链接]
 * @param  [type] $HQMusicUrl   [高质量音乐链接，WIFI环境优先使用该链接播放音乐]
 * @param  [type] $ThumbMediaId [缩略图的媒体id，通过上传多媒体文件，得到的id]
 * @return [type]               [description]
 */
function returnMusic($postObj,$title,$description,$musicUrl,$HQMusicUrl,$ThumbMediaId){
    $fromUsername = $postObj->FromUserName;
    $toUsername = $postObj->ToUserName;
    $time = time();
    $textTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[music]]></MsgType>
        <Music>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <MusicUrl><![CDATA[%s]]></MusicUrl>
        <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
        <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
        </Music>
        </xml>";
    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $title,$description,$musicUrl,$HQMusicUrl,$ThumbMediaId);
    echo $resultStr;
    exit;
}

/**
 * 回复图文消息
 * @param  [type] $postObj [description]
 * @param  [type] $newsArr [arr]
 * @return [type]          [description]
 */
function returnNews($postObj,$newsArr){
    $fromUsername = $postObj->FromUserName;
    $toUsername = $postObj->ToUserName;
    $time = time();
    $num = count($newsArr);
    foreach ($newsArr as $key => $value) {
        $item .= addItem($newsArr[$key]['title'],$newsArr[$key]['description'],$newsArr[$key]['picurl'],$newsArr[$key]['url']);
    }
    $textTpl = "
    <xml>
    <ToUserName><![CDATA[$fromUsername]]></ToUserName>
    <FromUserName><![CDATA[$toUsername]]></FromUserName>
    <CreateTime>$time</CreateTime>
    <MsgType><![CDATA[news]]></MsgType>
    <ArticleCount>$num</ArticleCount>
    <Articles>
    ";
    $textTpl .= $item;
    $textTpl .= 
    "</Articles>
    </xml> 
    ";
    echo $textTpl;
    exit;
}

function addItem($title='',$description='',$picurl='',$url=''){
    $item = "<item>
            <Title><![CDATA[$title]]></Title>
            <Description><![CDATA[$description]]></Description>
            <PicUrl><![CDATA[$picurl]]></PicUrl>
            <Url><![CDATA[$url]]></Url>
            </item>
            ";
    return $item;
}



/**
      function
 */
function temp_display(){
    $function = __CLASS__.'_'.__FUNCTION__;
    $template_name = M('template')->where("function='$function'")->getField('template_name');
    $this->display($template_name);
}


/**
 * 发送客服文本信息
 * @param  [type] $openid  [description]
 * @param  [type] $content [description]
 * @return [type]          [description]
 */
function sendTextMsg($openid,$content){
	$url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.get_access_token();
	$jsonData = '{
	    "touser":"'.$openid.'",
	    "msgtype":"text",
	    "text":
	    {
	         "content":"'.$content.'"
	    }
	}';
	// echo $jsonData;
	$res = curl_post($url,$jsonData);
	return $res;
}


/**
 * [kuaidi description]
 * @return [type] [description]
 */
function kuaidi($com,$nu){
    $id  = 'a0c862c3dbc0ac8f';
    // $com = '';
    // $nu  = '';
// 返回类型： 
// 0：返回json字符串， 
// 1：返回xml对象， 
// 2：返回html对象， 
// 3：返回text文本。 
    $show = 0;
// 排序： 
// desc：按时间由新到旧排列， 
// asc：按时间由旧到新排列。 
// 不填默认返回倒序（大小写不敏感）
    $order = 'desc';

    $url = "http://api.kuaidi100.com/api?id=$id&com=$com&nu=$nu&show=$show&muti=1&order=$order";
    // echo $url;
    return xcurl($url);

}



/**

飞印打印机部分
 





 */

function testSendFormatedMessage(){
    $msgNo = time()+1;
    /*
     格式化的打印内容
    */
    $msgInfo = array (
            'memberCode'=>MEMBER_CODE,  
            'charge'=>'3000',  
            'customerName'=>'刘小姐',  
            'customerPhone'=>'13321332245',  
            'customerAddress'=>'五山华南理工',  
            'customerMemo'=>'请快点送货',  
            'msgDetail'=>'番茄炒粉@1000@1||客家咸香鸡@2000@1',  
            'deviceNo'=>DEVICE_NO,  
            'msgNo'=>$msgNo,
    );

    echo sendFormatedMessage($msgInfo);

    return $msgNo;
}

function testSendFreeMessage($content = ''){
    $msgNo = time()+1;
    /*
     自由格式的打印内容
    */

    $freeMessage = array(
        'memberCode'=>MEMBER_CODE, 
//         'msgDetail'=>
// '
//     北京订餐网欢迎您订购


// 条目         单价（元）    数量
// ------------------------------
// 番茄炒粉
//              10.0          1
// 客家咸香鸡
//              20.0          1

// 备注：请快点送货。
// ------------------------------
// 合计：30.0元 

// 送货地址：北京中关村科技大厦23楼
// 联系电话：1380017****
// 订购时间：2011-01-06 19:30:10
// ',
        'msgDetail' => $content,
        'deviceNo'=>DEVICE_NO, 
        'msgNo'=>$msgNo,
    );

    echo sendFreeMessage($freeMessage);

    return $msgNo;
}

/*
 * 查询打印状态
 */
function testQueryState($msgNo){
    $result = queryState($msgNo);

    echo $result;

    return $result;
}

/*
 * 测试获取设备列表
 */
function testListDevice(){

    echo listDevice();
}


function testListException(){

    echo listException();
}


//----------------------以下是接口定义实现，第三方应用可根据具体情况直接修改----------------------------

function sendFreeMessage($msg) {
    $msg['reqTime'] = number_format(1000*time(), 0, '', '');
    $content = $msg['memberCode'].$msg['msgDetail'].$msg['deviceNo'].$msg['msgNo'].$msg['reqTime'].FEYIN_KEY;
    $msg['securityCode'] = md5($content);
    $msg['mode']=2;

    return sendMessage($msg);
}

function sendFormatedMessage($msgInfo) {
    $msgInfo['reqTime'] = number_format(1000*time(), 0, '', '');
    $content = $msgInfo['memberCode'].$msgInfo['customerName'].$msgInfo['customerPhone'].$msgInfo['customerAddress'].$msgInfo['customerMemo'].$msgInfo['msgDetail'].$msgInfo['deviceNo'].$msgInfo['msgNo'].$msgInfo['reqTime'].FEYIN_KEY;

    $msgInfo['securityCode'] = md5($content);
    $msgInfo['mode']=1;
    
    return sendMessage($msgInfo);
}


function sendMessage($msgInfo) {
    $client = new HttpClient(FEYIN_HOST,FEYIN_PORT);
    if(!$client->post('/api/sendMsg',$msgInfo)){ //提交失败
        return 'faild';
    }
    else{
        return $client->getContent();
    }
}

function queryState($msgNo){
    $now = number_format(1000*time(), 0, '', '');
    $client = new HttpClient(FEYIN_HOST,FEYIN_PORT);
    if(!$client->get('/api/queryState?memberCode='.MEMBER_CODE.'&reqTime='.$now.'&securityCode='.md5(MEMBER_CODE.$now.FEYIN_KEY.$msgNo).'&msgNo='.$msgNo)){ //请求失败
        return 'faild';
    }
    else{
        return $client->getContent();
    }
}

function listDevice(){
    $now = number_format(1000*time(), 0, '', '');
    $client = new HttpClient(FEYIN_HOST,FEYIN_PORT);
    if(!$client->get('/api/listDevice?memberCode='.MEMBER_CODE.'&reqTime='.$now.'&securityCode='.md5(MEMBER_CODE.$now.FEYIN_KEY))){ //请求失败
        return 'faild';
    }
    else{
        /***************************************************
        解释返回的设备状态
        格式：
        <device id="4600006007272080">  
        <address>广东**</address>
        <since>2010-09-29</since>
        <simCode>135600*****</simCode>
        <lastConnected>2011-03-09  19:39:03</lastConnected>
        <deviceStatus>离线 </deviceStatus>
        <paperStatus></paperStatus>
        </device>
        **************************************************/

        $xml = $client->getContent();
        $sxe = new SimpleXMLElement($xml);
        foreach($sxe->device as $device) {
            $id = $device['id'];
            echo "设备编码：$id    ";
            
            $deviceStatus = $device->deviceStatus;
            echo "状态：$deviceStatus";
            echo '<br>';
        }
    }
}


function listException(){
    $now = number_format(1000*time(), 0, '', '');
    $client = new HttpClient(FEYIN_HOST,FEYIN_PORT);
    if(!$client->get('/api/listException?memberCode='.MEMBER_CODE.'&reqTime='.$now.'&securityCode='.md5(MEMBER_CODE.$now.FEYIN_KEY))){ //请求失败
        return 'faild';
    }
    else{
        return $client->getContent();
    }
}
